package com.starsea.book.ui.config

import android.app.Application
import android.content.Context
import androidx.lifecycle.MutableLiveData
import com.google.gson.JsonParser
import com.starsea.book.R
import com.starsea.book.base.BaseViewModel
import com.starsea.book.constant.AppConst
import com.starsea.book.data.appDb
import com.starsea.book.help.AppWebDav
import com.starsea.book.help.book.BookHelp
import com.starsea.book.help.http.newCallResponseBody
import com.starsea.book.help.http.okHttpClient
import com.starsea.book.help.http.text
import com.starsea.book.ui.newpage.entity.BaseEntity
import com.starsea.book.ui.newpage.entity.HomeBannerEntity
import com.starsea.book.ui.newpage.utils.gsonNormal
import com.starsea.book.utils.FileUtils
import com.starsea.book.utils.LogUtils
import com.starsea.book.utils.toastOnUi
import okhttp3.RequestBody.Companion.toRequestBody

class ConfigViewModel(application: Application) : BaseViewModel(application) {

    val dealResult = MutableLiveData<BaseEntity<HomeBannerEntity>>()

    fun upWebDavConfig() {
        execute {
            AppWebDav.upConfig()
        }
    }

    fun clearCache() {
        execute {
            BookHelp.clearCache()
            FileUtils.delete(context.cacheDir.absolutePath)
        }.onSuccess {
            context.toastOnUi(R.string.clear_cache_success)
        }
    }

    fun clearWebViewData() {
        execute {
            FileUtils.delete(context.getDir("webview", Context.MODE_PRIVATE))
        }.onSuccess {
            context.toastOnUi(R.string.success)
        }
    }

    fun shrinkDatabase() {
        execute {
            appDb.openHelper.writableDatabase.execSQL("VACUUM")
        }.onSuccess {
            context.toastOnUi(R.string.success)
        }
    }

    //协议类型(LOGON:注册协议;HIDE:隐私协议;MEMBER:会员协议)
    fun getDeal(type: String) {
        execute {
            okHttpClient.newCallResponseBody {
                url(AppConst.BASE_URL.plus("front-api/appAgreementVersion/getAppAgreement?type=${type}"))
                    .post("".toRequestBody())
            }.text().let {
                LogUtils.e(">>> ", "it = " + it)
                val objects = JsonParser.parseString(it).asJsonObject
                val status = objects.get("status").asInt
                val msg = objects.get("msg").asString
                if (status == 200) {
                    LogUtils.e(">>>> ", "data = " + it)
                    val entity: BaseEntity<HomeBannerEntity> =
                        it.gsonNormal(HomeBannerEntity::class.java)
                    dealResult.postValue(entity)
                } else {
                    errorResult.postValue(msg)
                }

            }
        }.onError {
            context.toastOnUi(it.localizedMessage ?: "ERROR")
        }
    }
}
